package com.simple.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.crypto.SecureUtil;
import com.simple.common.Result;
import com.simple.dto.UserDTO;
import com.simple.mapper.AmountMapper;
import com.simple.mapper.BillMapper;
import com.simple.mapper.IncomeMapper;
import com.simple.mapper.UserMapper;
import com.simple.pojo.Amount;
import com.simple.pojo.Bill;
import com.simple.pojo.Income;
import com.simple.pojo.User;
import com.simple.service.AmountService;
import com.simple.service.BillService;
import com.simple.service.UserService;
import com.simple.utils.BeanConverterUtil;
import com.simple.utils.SimpleUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName UserServiceImpl
 * @Author SimpleTree
 **/
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private IncomeMapper incomeMapper;
    @Autowired
    private AmountService amountService;
    @Resource
    private BillService billService;
    @Autowired
    private BeanConverterUtil beanConverterUtil;

    @Override
    public Result login(UserDTO userDTO) {
        User user = userMapper.login(userDTO.getUsername());
        if (userDTO.getPassword().equals(SimpleUtil.deEncryPwd(user.getPassword()))) {
            return Result.of(user);
        }
        return Result.error();
    }

    @Override
    public List<UserDTO> getUsers(UserDTO userDTO) {
        List<User> users = userMapper.selectAll();
        List<UserDTO> userDTOs = new ArrayList<>();
        for (User user : users) {
            UserDTO dto = beanConverterUtil.toUserDTO(user);
            if ("admin".equals(user.getUsername())) {
                continue;
            }
            //余额
            dto.setTotalMoney(amountService.getTotalMoney(user.getId()));

            //本月收入
            List<Income> incomes = incomeMapper.getIncomes(user.getId());
            if (CollUtil.isNotEmpty(incomes)) {
                Income income = incomes.get(0);
                dto.setIncome(income.getSalary());
            }else {
                dto.setIncome(0D);
            }

            //本月支出
            Double monthBillMoney = billService.getMonthBillMoney(user.getId());
            dto.setPay(monthBillMoney);

            userDTOs.add(dto);
        }
        return userDTOs;
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void updateUser(UserDTO userDTO) {
        userMapper.updateByPrimaryKeySelective(beanConverterUtil.toUser(userDTO));
    }
}
